package com.iemes.controller.equip;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.EquipCategoryFormMap;
import com.iemes.entity.ErpEquipmentapply;
import com.iemes.entity.ResFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.mapper.equip.EquipCategoryMapper;
import com.iemes.plugin.PageView;
import com.iemes.upload.UploadUtil;
import com.iemes.util.Common;
import com.iemes.util.ExcelUtil;


@RequestMapping("equip")
@Controller
public class EquipCategoryController extends BaseController {
	@Inject
	private EquipCategoryMapper categoryMapper;

	@RequestMapping(value = "equip_category", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String examinepru(Model model) {
		// 种类表信息
		List<EquipCategoryFormMap> categoryFormMap = categoryMapper
				.findByWhere(new EquipCategoryFormMap());

		List<ResFormMap> findByRes = findByRes();
		model.addAttribute("categoryFormMap", categoryFormMap);
		model.addAttribute("res", findByRes);
		return Common.BACKGROUND_PATH + "/equip/category/equipbom_list";

	}

	@ResponseBody
	@RequestMapping("equip_categoryByPage")
	public PageView findByPage(String pageNow, String pageSize) {
		EquipCategoryFormMap equipCategoryFormMap = getFormMap(EquipCategoryFormMap.class);
		if (equipCategoryFormMap.get("categoryName") != null) {
			equipCategoryFormMap.set("categoryName",
					"%" + equipCategoryFormMap.get("categoryName") + "%");
		}
		equipCategoryFormMap = toFormMap(equipCategoryFormMap, pageNow,
				pageSize, equipCategoryFormMap.getStr("orderby"));
		List<EquipCategoryFormMap> findByPage = categoryMapper
				.findByPage(equipCategoryFormMap);
		pageView.setRecords(findByPage);
		return pageView;
	}

	@RequestMapping("equip_categoryAdd")
	public String addUI(Model model, HttpServletRequest request)
			throws Exception {
		return Common.BACKGROUND_PATH + "/equip/category/equipbom_add";
	}

	@ResponseBody
	@RequestMapping("equipbom_categoryaddEntity")
	// @Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module = "设备种类", methods = "设备-新增种类")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity() throws Exception {
		EquipCategoryFormMap equipCategoryFormMap = getFormMap(EquipCategoryFormMap.class);
		if (equipCategoryFormMap == null || equipCategoryFormMap.size() == 0) {
			return "false";
		}
		equipCategoryFormMap.set("status", 1);
		categoryMapper.addEntity(equipCategoryFormMap);

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "category_deleteEntity")
	@SystemLog(module = "设备种类", methods = "设备-删除种类")
	// 凡需要处理业务逻辑的.都需要记录操作日志category_adds
	public String deleteEntity() throws Exception {
		EquipCategoryFormMap equipCategoryFormMap = getFormMap(EquipCategoryFormMap.class);
		String[] ids = getParaValues("ids");
		String arr = ids[0];
		String[] str = arr.split(",");
		for (int i = 0; i < str.length; i++) {
			equipCategoryFormMap.set("status", 2);
			equipCategoryFormMap.put("id", str[i]);
			categoryMapper.editEntity(equipCategoryFormMap);
		}
		return "success";
	}

	@RequestMapping("category_edit")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		EquipCategoryFormMap findbyFrist = categoryMapper.findbyFrist("id", id,
				EquipCategoryFormMap.class);
		model.addAttribute("equipAll", findbyFrist);
		return Common.BACKGROUND_PATH + "/equip/category/equipbom_edit";
	}

	@ResponseBody
	@RequestMapping(value = "category_editEntity")
	@SystemLog(module = "设备种类", methods = "设备-修改种类")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity() throws Exception {
		EquipCategoryFormMap equipCategoryFormMap = getFormMap(EquipCategoryFormMap.class);
		categoryMapper.editEntity(equipCategoryFormMap);
		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "category_exportEntity")
	@SystemLog(module = "设备种类", methods = "设备-导出种类")// 凡需要处理业务逻辑的.都需要记录操作日志
	public String exportEntity(HttpServletResponse response,HttpServletRequest request) throws Exception {
		Connection conn = ExcelUtil.getConnection();
		try {
		PreparedStatement ps = conn
				.prepareStatement("SELECT * FROM erp_equipmentcategory");
		ResultSet rs = ps.executeQuery();		
		//标题
		String title[] = { "id","categoryName", "status" };
		// excel文件名
		String fileName =".xls";
		ExcelUtil.fillExcelData(request,response,rs, title ,fileName);
		
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (conn!=null) {
				conn.close();
			}
			
		}

		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value = "excel", method = RequestMethod.POST)
	@SystemLog(module = "设备种类", methods = "设备-导入种类")
	public String uploadExcel(
			@RequestParam(value = "attachs", required = false) MultipartFile attachs,
			HttpServletRequest request) {
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;
		EquipCategoryFormMap equipCategoryFormMap = getFormMap(EquipCategoryFormMap.class);
		try {
			fs = new POIFSFileSystem(attachs.getInputStream());
			wb = new HSSFWorkbook(fs);
			 // Excel的页签数量
            int sheet_size = wb.getNumberOfSheets();
			
		    for (int index = 0; index < sheet_size; index++) {
				HSSFSheet hssfSheet = wb.getSheetAt(index);// 获取第一个Sheet页
				if (hssfSheet != null) {
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow == null) {
							continue;
						}
						equipCategoryFormMap.set("categoryName",
								ExcelUtil.formatCell(hssfRow.getCell(1)));
						equipCategoryFormMap.set("status",
								ExcelUtil.formatCell(hssfRow.getCell(2)));
						equipCategoryFormMap.clear();
					}
				}
				
			}			
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "success";
	}
	
}
